package com.iot.manager.ui.activities;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.material.textfield.TextInputEditText;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.iot.manager.R;
import com.iot.manager.data.models.DeviceConfig;
import com.iot.manager.network.ApiService;
import com.iot.manager.network.RetrofitClient;
import com.iot.manager.utils.QRCodeUtils;
import com.iot.manager.utils.DeviceWifiManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class DeviceConfigActivity extends AppCompatActivity {
    private static final int PERMISSION_REQUEST_CAMERA = 1;
    private static final int PICK_IMAGE = 2;
    private static final int SCAN_QR_REQUEST_CODE = 3;

    private String deviceId;
    private ApiService apiService;
    private DeviceWifiManager wifiManager;
    private DeviceConfig deviceConfig;

    private TextView tvStatus;
    private ProgressBar progressBar;
    private Button btnScanQR;
    private Button btnLoadQR;
    private Button btnConnectWifi;
    private Button btnSave;

    private TextInputEditText etSamplingInterval;
    private TextInputEditText etUploadInterval;
    private TextInputEditText etTemperatureHigh;
    private TextInputEditText etTemperatureLow;
    private TextInputEditText etHumidityHigh;
    private TextInputEditText etHumidityLow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_config);

        deviceId = getIntent().getStringExtra("deviceId");
        if (deviceId == null) {
            finish();
            return;
        }

        setupToolbar();
        initViews();
        setupListeners();
        loadDeviceConfig();
    }

    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle(R.string.device_config);
        }
    }

    private void initViews() {
        tvStatus = findViewById(R.id.tv_status);
        progressBar = findViewById(R.id.progress_bar);
        btnScanQR = findViewById(R.id.btn_scan_qr);
        btnLoadQR = findViewById(R.id.btn_load_qr);
        btnConnectWifi = findViewById(R.id.btn_connect_wifi);
        btnSave = findViewById(R.id.btn_save);

        etSamplingInterval = findViewById(R.id.et_sampling_interval);
        etUploadInterval = findViewById(R.id.et_upload_interval);
        etTemperatureHigh = findViewById(R.id.et_temperature_high);
        etTemperatureLow = findViewById(R.id.et_temperature_low);
        etHumidityHigh = findViewById(R.id.et_humidity_high);
        etHumidityLow = findViewById(R.id.et_humidity_low);

        apiService = RetrofitClient.getInstance().getApiService();
        wifiManager = new DeviceWifiManager(this);
    }

    private void setupListeners() {
        btnSave.setOnClickListener(v -> saveConfig());
        btnScanQR.setOnClickListener(v -> {
            Intent intent = new Intent(this, DeviceProvisioningActivity.class);
            startActivity(intent);
        });
        btnLoadQR.setOnClickListener(v -> {
            Intent intent = new Intent(this, DeviceProvisioningActivity.class);
            startActivity(intent);
        });
        btnConnectWifi.setOnClickListener(v -> connectToWifi());
    }

    private void showProgress(boolean show) {
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        btnScanQR.setEnabled(!show);
        btnLoadQR.setEnabled(!show);
        btnConnectWifi.setEnabled(!show);
        btnSave.setEnabled(!show);
    }

    private void updateStatus(String status) {
        tvStatus.setText(status);
    }

    private void loadDeviceConfig() {
        showProgress(true);
        apiService.getDeviceConfig(deviceId).enqueue(new Callback<DeviceConfig>() {
            @Override
            public void onResponse(Call<DeviceConfig> call, Response<DeviceConfig> response) {
                showProgress(false);
                if (response.isSuccessful() && response.body() != null) {
                    deviceConfig = response.body();
                    updateUI();
                } else {
                    try {
                        String errorBody = response.errorBody() != null ? response.errorBody().string() : "";
                        Toast.makeText(DeviceConfigActivity.this, 
                            getString(R.string.error_loading_config) + ": " + errorBody, 
                            Toast.LENGTH_SHORT).show();
                    } catch (IOException e) {
                        Toast.makeText(DeviceConfigActivity.this, 
                            R.string.error_loading_config, 
                            Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<DeviceConfig> call, Throwable t) {
                showProgress(false);
                Toast.makeText(DeviceConfigActivity.this, R.string.network_error, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void updateUI() {
        if (deviceConfig != null) {
            etSamplingInterval.setText(String.valueOf(deviceConfig.getSamplingInterval()));
            etUploadInterval.setText(String.valueOf(deviceConfig.getUploadInterval()));

            DeviceConfig.AlarmThresholds alarmThresholds = deviceConfig.getAlarmThresholds();
            if (alarmThresholds != null) {
                DeviceConfig.TemperatureThresholds tempThresholds = alarmThresholds.getTemperature();
                DeviceConfig.HumidityThresholds humidityThresholds = alarmThresholds.getHumidity();

                if (tempThresholds != null) {
                    etTemperatureHigh.setText(String.valueOf(tempThresholds.getHigh()));
                    etTemperatureLow.setText(String.valueOf(tempThresholds.getLow()));
                }

                if (humidityThresholds != null) {
                    etHumidityHigh.setText(String.valueOf(humidityThresholds.getHigh()));
                    etHumidityLow.setText(String.valueOf(humidityThresholds.getLow()));
                }
            }
        }
    }

    private void saveConfig() {
        if (deviceConfig == null) {
            Toast.makeText(this, R.string.error_no_config, Toast.LENGTH_SHORT).show();
            return;
        }

        updateStatus(getString(R.string.saving_config));
        apiService.updateDeviceConfig(deviceId, deviceConfig).enqueue(new Callback<DeviceConfig>() {
            @Override
            public void onResponse(Call<DeviceConfig> call, Response<DeviceConfig> response) {
                if (response.isSuccessful()) {
                    runOnUiThread(() -> {
                        Toast.makeText(DeviceConfigActivity.this, R.string.config_updated, Toast.LENGTH_SHORT).show();
                        setResult(RESULT_OK);
                        finish();
                    });
                } else {
                    runOnUiThread(() -> {
                        updateStatus(getString(R.string.error_saving_config));
                        Toast.makeText(DeviceConfigActivity.this, R.string.error_saving_config, Toast.LENGTH_SHORT).show();
                    });
                }
            }

            @Override
            public void onFailure(Call<DeviceConfig> call, Throwable t) {
                runOnUiThread(() -> {
                    updateStatus(getString(R.string.error_saving_config));
                    Toast.makeText(DeviceConfigActivity.this, R.string.error_saving_config, Toast.LENGTH_SHORT).show();
                });
            }
        });
    }

    private void checkCameraPermissionAndScan() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    PERMISSION_REQUEST_CAMERA);
        } else {
            startQRScanner();
        }
    }

    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, PICK_IMAGE);
    }

    private void connectToWifi() {
        if (deviceConfig == null) {
            Toast.makeText(this, R.string.error_no_wifi_config, Toast.LENGTH_SHORT).show();
            return;
        }

        updateStatus(getString(R.string.connecting_wifi));
        String ssid = deviceConfig.getWifiSsid();
        String password = deviceConfig.getWifiPassword();
        wifiManager.connectToDeviceWifi(ssid, password, deviceId, 
            new DeviceWifiManager.ConnectionCallback() {
                @Override
                public void onSuccess() {
                    updateStatus(getString(R.string.connected_to_device));
                    btnConnectWifi.setEnabled(false);
                }

                @Override
                public void onError(String error) {
                    updateStatus(getString(R.string.error_connecting_device));
                    Toast.makeText(DeviceConfigActivity.this, error, Toast.LENGTH_SHORT).show();
                }
            });
    }

    private void startQRScanner() {
        IntentIntegrator integrator = new IntentIntegrator(this);
        integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE);
        integrator.setPrompt(getString(R.string.scan_qr_prompt));
        integrator.setCameraId(0);
        integrator.setBeepEnabled(false);
        integrator.setBarcodeImageEnabled(true);
        integrator.initiateScan();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
} 